package com.golden.zip.module;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.golden.zip.bean.Zip;
import com.golden.zip.filter.XFilter;
import com.golden.zip.query.ZipQuery;
import com.golden.zip.util.ZipUtils;

@IocBean
@At("/main")
@Ok("json")
@Fail("http:500")
public class ZipFileModule {

    @Inject
    protected Dao dao;
    
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "zip"+File.separator+"upload";
    //解压文件存储目录
    private static final String FOLDER = "zip"+File.separator+"folder";
    
    @At
    @Ok("jsp:pages/zipList")
    public void zipList(){
    }
    
    /**
     * 查询树列表第一级
     * @return
     */
    @At
    public List<ZipQuery> queryFirst() {
        Sql sql = Sqls.create("select t.id,t.name,t.servername,t.mod_flag as modFlag,t.parent_id as parentId,t.order_id as orderId,(SELECT COUNT(0) FROM t_zip_file C WHERE C.PARENT_ID = t.id) as childCount,CASE (SELECT COUNT(0) FROM t_zip_file C WHERE C.PARENT_ID = t.id) WHEN 0 THEN 'open'  ELSE 'closed' END AS state  from t_zip_file t  where t.parent_id=-1 order by t.order_id");
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(ZipQuery.class));
        dao.execute(sql);
        List<ZipQuery> list = sql.getList(ZipQuery.class);
        return list; 
    }
    
    /**
     * 查询树列表下一级
     * @param parentId
     * @return
     */
    @At
    public List<ZipQuery> queryNext(@Param("parentId")String parentId){
        Sql sql = Sqls.create("select t.id,t.name,t.servername,t.mod_flag as modFlag,t.parent_id as parentId,t.order_id as orderId,to_char(t.opertime,'yyyy-MM-dd') as operTime,(SELECT COUNT(0) FROM t_zip_file C WHERE C.PARENT_ID = t.id) as childCount,CASE (SELECT COUNT(0) FROM t_zip_file C WHERE C.PARENT_ID = t.id) WHEN 0 THEN 'open'  ELSE 'closed' END AS state,t.remark,t.filename  from t_zip_file t  where t.parent_id=@parentId order by t.order_id");
        sql.params().set("parentId", parentId);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(ZipQuery.class));
        dao.execute(sql);
        List<ZipQuery> list = sql.getList(ZipQuery.class);
        return list;
    }
    
    /**
     * 新增文件夹
     * @param param
     * @return
     */
    @At
    public Integer insertZipFolder(@Param("..")HashMap<String,Object> param){
        Zip zip=new Zip();
        zip.setName(String.valueOf(param.get("name")));
        zip.setModFlag(0);
        zip.setOrderId(String.valueOf(param.get("orderId")));
        zip.setParentId(String.valueOf(param.get("parentId")));
        Date nowTime=new Date(); 
        zip.setOperTime(nowTime);        
        Zip result=dao.insert(zip);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    @At
    @Ok("jsp:pages/webuploader")
    public void upload(){
    }
    
    @At
    @Ok("json")
    @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
    public Map<String,Object> uploadZipFile(@Param("file") TempFile tf){
        // 这个路径相对当前应用的目录
        HttpServletRequest request=XFilter.requests.get();
        String uploadPath = request.getSession().getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        String folderPath=request.getSession().getServletContext().getRealPath("./") + File.separator + FOLDER;
        Map<String,Object> resultMap=new HashMap<String,Object>();
        try {
            //上传的文件保存在临时目录，先把临时目录中的zip或rar文件放在uolpad文件夹里
            tf.write(uploadPath+File.separator+tf.getSubmittedFileName());
            //删除临时文件
            tf.delete();
            //解压已上传的文件
            String fileName=tf.getSubmittedFileName();
            String resultPath="";
            if(fileName.endsWith(".rar")){
                resultPath=ZipUtils.unRarFile(uploadPath+File.separator+tf.getSubmittedFileName(), folderPath);
            }else{
                resultPath=ZipUtils.unZipFiles(new File(uploadPath+File.separator+tf.getSubmittedFileName()), folderPath);
            }
            //返回indexhtml的路径
            resultMap.put("path", resultPath.split("folder")[1]);
            //上传的压缩包名
            resultMap.put("fileName", tf.getSubmittedFileName());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
    /**
     * 新增文件
     * @param param
     * @return
     */
    @At
    public Integer insertProject(@Param("..")HashMap<String,Object> param){
        Zip zip=new Zip();
        zip.setName(String.valueOf(param.get("name")));
        zip.setModFlag(1);
        zip.setOrderId(String.valueOf(param.get("orderId")));
        zip.setParentId(String.valueOf(param.get("parentId")));
        zip.setRemark(String.valueOf(param.get("remark")));
        zip.setServerName(String.valueOf(param.get("serverName")));
        zip.setFilename(String.valueOf(param.get("filename")));
        Date nowTime=new Date(); 
        zip.setOperTime(nowTime); 
        Zip result=dao.insert(zip);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 修改文件夹名称
     * @param param
     * @return
     */
    @At
    public Integer updateZipFolder(@Param("..")HashMap<String,Object> param){
        Zip zip=new Zip();
        zip.setId(String.valueOf(param.get("id")));
        zip.setName(String.valueOf(param.get("name")));
        zip.setOrderId(String.valueOf(param.get("orderId")));
        Integer result=dao.updateIgnoreNull(zip);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 修改文件名称或备注
     * @param param
     * @return
     */
    @At
    public Integer updateProject(@Param("..")HashMap<String,Object> param){
        Zip zip=new Zip();
        zip.setId(String.valueOf(param.get("id")));
        zip.setName(String.valueOf(param.get("name")));
        zip.setOrderId(String.valueOf(param.get("orderId")));
        zip.setRemark(String.valueOf(param.get("remark")));
        Integer result=dao.updateIgnoreNull(zip);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 删除文件
     * @param param
     * @return
     */
    @At
    public Integer deleteProject(@Param("id")String id){
        Zip zip=new Zip();
        zip.setId(id);
        Zip resultZip = dao.fetch(Zip.class,id);
        Integer result=0;
        HttpServletRequest request=XFilter.requests.get();
        String uploadPath = request.getSession().getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        String folderPath=request.getSession().getServletContext().getRealPath("./") + File.separator + FOLDER;
        //删除上传的压缩包
        boolean deleteZip=ZipUtils.deleteFile(uploadPath+File.separator+resultZip.getFilename());
        boolean deleteFolder=ZipUtils.deleteDirectory(folderPath+File.separator+resultZip.getServerName().substring(0, resultZip.getServerName().length()-11));
        if(deleteZip && deleteFolder){
            result=dao.delete(zip);
        }
        return result;
    }
    
    @At
    @Ok("json")
    public ZipQuery queryMaxOrderId(@Param("parentId")String parentId){
        Sql sql = Sqls.fetchEntity("select * from (select  t.id,t.name,t.servername,t.mod_flag as modFlag,t.parent_id as parentId,t.order_id as orderId from T_ZIP_FILE  t  where 1=1   and t.parent_id=@parentId order by t.order_id desc) where rownum = 1");
        sql.params().set("parentId",parentId);
        Entity<ZipQuery> entity =dao.getEntity(ZipQuery.class);
        sql.setEntity(entity);
        dao.execute(sql);
        ZipQuery zipQuery= sql.getObject(ZipQuery.class);
        if(zipQuery!=null && zipQuery.getOrderId()!=null){
            zipQuery.setOrderId(zipQuery.getOrderId()+1);
        }
        return zipQuery;
    }
}
